package com.rc.saas.tenant.controller.enterprise;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.model.enterprise.RcEnterpriseGainGradeSetting;
import com.rc.saas.tenant.model.enterprise.RcEnterpriseGainSetting;
import com.rc.saas.tenant.model.enterprise.RcEnterpriseGainSettingExample;
import com.rc.saas.tenant.model.enterprise.RcEnterpriseLevelSetting;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.enterprise.RcEnterpriseGainGradeSettingService;
import com.rc.saas.tenant.service.enterprise.RcEnterpriseGainSettingService;
import com.rc.saas.tenant.service.enterprise.RcEnterpriseLevelSettingService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.enterprise.EnterpriseGainSettingVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/enterprise/gain/setting")
public class RcEnterpriseGainSettingController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RcEnterpriseGainSettingService enterpriseGainSettingService;

    @Autowired
    private RcEnterpriseLevelSettingService enterpriseLevelSettingService;

    @Autowired
    private RcEnterpriseGainGradeSettingService entGradeSettingService;

    @Autowired
    private UploadComponent uploadComponent;


    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/enterprise/gain/enterpriseGain";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addEnterpriseGain(Model model) {
        List<RcEnterpriseLevelSetting> level = enterpriseLevelSettingService.listLevel();
        model.addAttribute("level", level);
        return "/templates/enterprise/gain/addEnterpriseGain";
    }

    @ResponseBody
    @RequestMapping("/listPageGainSetting")
    public WebPageInfo listPageGainSetting(String gainName, Integer pageNo, Integer pageSize) {
        PageInfo<RcEnterpriseGainSetting> pageInfo = enterpriseGainSettingService.listPageEnterpriseGainSetting(gainName, pageNo, pageSize);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出企业权益列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(String gainName, @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                            @RequestParam(value = "pageSize",defaultValue = "1000") Integer pageSize, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            PageInfo<RcEnterpriseGainSetting> pageInfo = enterpriseGainSettingService.listPageEnterpriseGainSetting(gainName, pageNo, pageSize);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("企业权益列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RcEnterpriseGainSetting.class).sheet("企业权益列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出企业权益列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("/updateGainSettingStatus")
    public TResponse updateGainSettingStatus(Long id, String status) {
        RcEnterpriseGainSetting enterpriseGainSetting = enterpriseGainSettingService.selectByPrimaryKey(id);
        enterpriseGainSetting.setStatus(status);
        enterpriseGainSettingService.updateByPrimaryKeySelective(enterpriseGainSetting);
        return TResponse.SUCCESS();
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String editEnterpriseGain(Model model, @PathVariable("id") Long id) {
        List<RcEnterpriseLevelSetting> level = enterpriseLevelSettingService.listLevel();
        RcEnterpriseGainSetting enterpriseGainSetting = enterpriseGainSettingService.selectByPrimaryKey(id);
        List<RcEnterpriseGainGradeSetting> gradeSettingList = entGradeSettingService.listGradeByGain(enterpriseGainSetting.getEnterpriseGainId());
        enterpriseGainSetting.setGradeSettingList(gradeSettingList);
        model.addAttribute("level", level);
        model.addAttribute("enterpriseGainSetting", enterpriseGainSetting);
        return "/templates/enterprise/gain/editEnterpriseGain";
    }

    @ResponseBody
    @RequestMapping("/deleteEnterprisGain")
    public TResponse deleteEnterprisGain(Long id) {
        enterpriseGainSettingService.deleteGainSetting(id);
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/addEntGainSetting", method = RequestMethod.POST, produces = "application/json")
    public TResponse addEntGainSetting(@RequestBody EnterpriseGainSettingVo vo) {

        RcEnterpriseGainSettingExample example = new RcEnterpriseGainSettingExample();
        example.createCriteria().andEnterpriseLevelEqualTo(vo.getGainSetting().getEnterpriseLevel()).andGainTypeEqualTo(vo.getGainSetting().getGainType());
        List<RcEnterpriseGainSetting> list = enterpriseGainSettingService.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return TResponse.FAIL("失败：当前等级已存在其他权益");
        }

        enterpriseGainSettingService.addEnterpriseGainSetting(vo.getGainSetting(), vo.getGradeList());
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/updateEntGainSetting")
    public TResponse updateEntGainSetting(@RequestBody EnterpriseGainSettingVo vo) {
        List<RcEnterpriseGainGradeSetting> addGradeList = vo.getGradeList().stream().filter(setting -> setting.getGainGradeId() == null).collect(Collectors.toList());
        List<RcEnterpriseGainGradeSetting> editGradeList = vo.getGradeList().stream().filter(setting -> setting.getGainGradeId() != null).collect(Collectors.toList());
        enterpriseGainSettingService.updateEnterpriseGainSetting(vo.getGainSetting(), addGradeList, editGradeList, vo.getDelGradeList());
        return TResponse.SUCCESS();
    }


    @ResponseBody
    @RequestMapping("/listPageEntGainGrade")
    public WebPageInfo listPageEntGainGrade(Long enterpriseGainId, Integer pageNo, Integer pageSize) {
        PageInfo<RcEnterpriseGainGradeSetting> pageInfo = entGradeSettingService.listPageEnterpriseGainGrade(enterpriseGainId, pageNo, pageSize);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    @ResponseBody
    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    public TResponse uploadFile(@RequestParam(value = "file", required = false) MultipartFile file) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (file != null && file.getSize() != 0 && file.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file);
            return TResponse.SUCCESS_DATA(imgUrl);

        }
        return TResponse.SUCCESS();
    }


}
